//
//  EssenceCommentViewController.swift
//  FM
//
//  Created by x on 2017/10/13.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class EssenceCommentViewController: UIViewController {
    
    /// 保存当前的社区那个内容
    var essence:Essence?
    
    /// 记录当前加载评论的下标值
    var index:Int = 0
    
    
    init(model:Essence) {
        essence = model
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    /// 初始化
    func setupUI() -> Void {
        view.backgroundColor = UIColor.white
        
        navigationItem.title = "社区详情"
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "back", target: self, action: #selector(backClick))
        
        view.addSubview(essenceCommentTableView)
        
        //1.加载评论数据
        loadComment(offset: 0)
    }
    
    override func viewWillLayoutSubviews() {
         super.viewWillLayoutSubviews()
        essenceCommentTableView.frame = view.bounds
    }
    
    /// 上拉刷新加载更多数据
    func loadMoreCommentData() -> Void {
        //判断还有没有评论加载
        if commentList.count < Int((essence?.commentnum)!)! {
            index += 1
            let num  = index * 10
            loadComment(offset: num)
        }else {
            SVProgressHUD.show(UIImage.init(named: "")!, status: "已经是最新数据了!")
            essenceCommentTableView.mj_footer.endRefreshing()
        }
    }
    
    /// 加载评论数据
    ///
    /// - Parameter offset: <#offset description#>
    func loadComment(offset:Int) -> Void {
        NetWorTools.shareNetWorkTools().loadComments(post_id: (essence?.id)!, offset: offset, successCallBack: { (data) in
            self.commentList += data
            self.essenceCommentTableView.reloadData()
        }) { (error) in
            print("loadCommentData=======%@",error)
        }
    }
    
    /// 返回按钮
    func backClick() -> Void {
        navigationController?.popViewController(animated: true)
    }
    
    //MARK: -- 懒加载
    private lazy var essenceCommentTableView:UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        //注册cell
        tableView.register(EssenceCell.self, forCellReuseIdentifier: essenceCellIdentifier)
        tableView.register(EssenceCommentCell.self, forCellReuseIdentifier: essenceCommentCellIdentifier)
        
        //上拉刷新
        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreCommentData))
        
        return tableView
    }()
    
    /// 表格数据源
    fileprivate lazy var commentList:[EssenceComment] = [EssenceComment]()
    
    /// 缓存行高
    fileprivate lazy var cachesHeight:[String:CGFloat] = [String:CGFloat]()
    
    deinit {
        print("EssenceCommentViewController=====deinit")
    }
}

/// 社区cell的标示
private let essenceCellIdentifier = "essenceCellIdentifier"

/// 社区评论的cell标示
private let essenceCommentCellIdentifier = "essenceCommentCellIdentifier"

extension EssenceCommentViewController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commentList.count + 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: essenceCellIdentifier) as! EssenceCell
            cell.model = essence
            cell.isCornerRadius = false
            
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: essenceCommentCellIdentifier) as! EssenceCommentCell
            cell.essenceComment = commentList[indexPath.row-1]
            
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: essenceCellIdentifier) as! EssenceCell
            
            return cell.rowHeight(essence: essence!)
        }else {
            //1.首先重缓存中取cell的高度
            
            let model = commentList[indexPath.row-1]
            let height = cachesHeight[model.id!]
            
            //如果缓存中有直接返回
            guard height == nil else {
                return height!
            }
            
            //2.如果缓存中没有
            let cell = tableView.dequeueReusableCell(withIdentifier: essenceCommentCellIdentifier) as! EssenceCommentCell
            
            let rowHeight = cell.rowHeight(model: model)
            
            //3.把得到的高度存到内存中
            cachesHeight[model.id!] = rowHeight
            
            return rowHeight

        }
    }
}

















